package org.grow.jssp.controller;

import org.grow.jssp.dao.DownloadLogMapper;
import org.grow.jssp.entity.DownloadLog;
import org.grow.jssp.entity.JsspFile;
import org.grow.jssp.service.FileLambdaOps;
import org.grow.jssp.service.FileOps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * @Author: xwg
 * @CreateDate: 2022/3/11
 */

@Controller
public class DownloadController {
    @Value("${target}")
    private String target;
    @Autowired
    private FileOps fileOps;
    @Autowired
    private FileLambdaOps fileLambdaOps;
    @Autowired
    private DownloadLogMapper downloadLogMapper;

    //    访问待下载的文件页面
    @GetMapping("/repository")
    public ModelAndView repository(HttpServletRequest request) {
//        String target = System.getProperty("user.home");

//        System.out.println(target);
/*        File file = new File(target);
//
        File[] oldList = file.listFiles();
//        过滤掉文件夹
        List<File> newList = new ArrayList<File>();
        for (int i = 0; i < oldList.length; i++) {
            File item = oldList[i];
            if (item.isFile()) {
                newList.add(item);
            }
        }
//         ["a.txt","b.txt"]
//        ["{title:"a.txt", size:10MB }","{title:"a.txt", size:2MB }"]
//        System.out.println(Arrays.toString(list));  映射f(x)
        ArrayList<JsspFile> finalList = new ArrayList<>();
        for (int i = 0; i < newList.size(); i++) {
            File item = newList.get(i);
            JsspFile jsspFile = new JsspFile();
            jsspFile.setTitle(item.getName());
            jsspFile.setSize((int)item.length());
            finalList.add(jsspFile);
        }
        System.out.println(newList);*/

//        List<JsspFile> finalList = this.fileOps.ops(target);
        List<JsspFile> finalList = this.fileLambdaOps.ops(target);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("repository");
        modelAndView.addObject("fileToDownload", finalList);
        return modelAndView;
    }

    @GetMapping("/download/{filename}")
    public void download(@PathVariable String filename,
                         HttpServletRequest request, HttpServletResponse response)  {

//        System.out.println("将要下载： " + filename);
//        String target = System.getProperty("user.home");

//        System.out.println(target);
        String t = target + File.separator + filename;
//        System.out.println(t);
        long length = new File(t).length();
//        准备开始下载
//        告诉浏览器内容类型不是html而是二进制流
//        response.setContentType("application/octet-stream");
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

//        response.addHeader("Content-Disposition",
//                "attachment;filename="+t);
        ContentDisposition c = ContentDisposition.attachment().filename(
                        filename, StandardCharsets.UTF_8)
                .build();
        System.out.println(c);
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, c.toString());

        response.setContentLength((int) length);

        DownloadLog downloadLog = new DownloadLog();
        downloadLog.setDownloadLogId(0);
        downloadLog.setDownloadTime(LocalDateTime.now());
        downloadLog.setFilename(filename);
        downloadLog.setTargetFile(t);
        String principle =(String) request.getSession().getAttribute("principle");
        downloadLog.setUsername(principle);
       try {
            byte[] buffer = new byte[1024000];
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(t));
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            while (true) {
                int r = in.read(buffer);
                if (r == -1) {
                    break;
                }
                out.write(buffer, 0, r);
            }
            out.flush();
            downloadLog.setState("success");
        } catch (IOException e) {
            downloadLog.setState("failure");
            e.printStackTrace();
        } finally {
            downloadLogMapper.insert(downloadLog);
        }


    }
}
